package search;

import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import fj.F;
import global.Global;

import reports.DetailReport;
import server.Initialize;
import server.db.DatabaseFunctor;
import server.db.StmtHelper;
import server.json.FunctionalJSON;
import server.objects.Photo;

import static server.db.StmtHelper.db;
import ajaxmethods.SessionMethod;

public class PerformMapSearch extends SessionMethod {

	String dialog = "mapsearch";
	String selectFields = "lat,lng,zillowID,useCode,price,finishedSQFT,bathrooms,bedrooms,(select concat(street,' ',city,', ',state,' ',zip))  as ADDRESS," +
			"ifnull((select image_url from photos where photos.zillowID=alllist.zillowID and photos.photo_num=1),'"+Photo.getNoPhotoURL()+"')image_url";
	private F<List<Map<String, String>>, DatabaseFunctor<List<Map<String,String>>>> getSearchQueryFromDlgFields = new F<List<Map<String, String>>, DatabaseFunctor<List<Map<String,String>>>>() {

		@Override
		public DatabaseFunctor<List<Map<String,String>>> f(List<Map<String, String>> arg0) {
			
			StmtHelper prep = db("select "+selectFields+" from alllist where ");
			for(int i=0; i< arg0.size(); i++)
			{
				Object fieldvalue = fieldsMap.get(arg0.get(i).get("fieldid"));
				if(arg0.get(i).get("datatype").equals("integer"))
					fieldvalue = Integer.parseInt((String)fieldvalue);
				if(arg0.get(i).get("dbname").equals("price"))
					fieldvalue = (Integer)fieldvalue*1000;
				if(i>0)
					prep.addSql(" and ");
				prep.addSql(arg0.get(i).get("dbname")+" "+arg0.get(i).get("searchtype")+" ").addVariable(fieldvalue);
			}
			return prep.collectIntoMaps;
		}
		
	};
	
	Map<String,String> fieldsMap = new HashMap();
	
	@Override
	public void perform(HttpServletRequest request, HttpServletResponse response) {
		super.perform(request, response);
		response.setContentType("text/json");
		String searchFieldsString = request.getParameter("fields");
		if(searchFieldsString!=null)
		{
			
			Boolean hasSearchParams = false;
			for(String field : searchFieldsString.split(","))
			{
				String[] fvPair = field.split(":");
				if(fvPair.length>1)
				{
					hasSearchParams=true;
					fieldsMap.put(fvPair[0],fvPair[1]);
				}
			}
			
			if(hasSearchParams)
			{
				try {
					JSONArray jsonArr = FunctionalJSON.mapToJSONArray.f(db("select fieldid,searchtype,dbname,datatype from inputfields where dialog=").addVariable(dialog)
						.addSql(" and fieldid in (").addIterableVariables(fieldsMap.keySet())
						.addSql(") ").collectIntoMaps.provideTo(getSearchQueryFromDlgFields).unsafeGet());
					Global global = new Global(request);
					if(jsonArr.length()>0) {
						global.setListingResults(jsonArr);
					}
					else
						global.setListingResults(null);
					
						StringBuffer sb = new StringBuffer();
						sb.append("<div id=\"listView\">");
						
						sb.append("<div id=\"action\"><a class=\"pageup disabled\" onclick=\"$('#scrollable').data('scrollable').seekTo(Math.max(0,$('#scrollable').data('scrollable').getIndex()-4));\" >&#x25B2;&#x25B2; page up</a><span style=\"padding:0px 1px;\">&nbsp;</span><a class=\"prev\" >&#x25B2; prev</a>" +
								"<span style=\"padding:0px 1px;\">&nbsp;</span><span style=\"padding:0px 10px;\">Displaying <span id=\"start\">1</span>&nbsp;to&nbsp;<span id=\"end\">4</span>&nbsp;of&nbsp;<span id=\"total\">&nbsp;"+jsonArr.length()+"&nbsp;</span></span><span style=\"padding:0px 1px;\">&nbsp;</span>" +
								"<a class=\"next\" >next &#x25BC;</a><span style=\"padding:0px 1px;\">&nbsp;</span><a class=\"pagedown\" onclick=\"$('#scrollable').data('scrollable').seekTo(Math.min($('#scrollable').data('scrollable').getSize()-1,$('#scrollable').data('scrollable').getIndex()+4));\" >page down &#x25BC;&#x25BC;</a></div>");
						sb.append("<script>$(document).ready(function(){$('#listView #scrollable').scrollable({vertical: true,touch:false, mousewheel: true," +
								"onSeek:function(){" +
								"if(this.getIndex()>0)\n" +
								" $('#action .pageup').removeClass('disabled'); " +
								"else  " +
								" $('#action .pageup').addClass('disabled');" +
								"if(this.getIndex()>=this.getSize()-1) " +
								" $('#action .pagedown').addClass('disabled'); " +
								"else  " +
								" $('#action .pagedown').removeClass('disabled');" +
								"$('#action #start').html(this.getIndex()+1);" +
								"$('#action #end').html(Math.min(this.getSize(),this.getIndex()+4));" +
								" }" +
								"});});</script>");
						
						sb.append("<div id=\"scrollable\" class=\"vertical\"><div class=\"items\">");
						for(int i = 0; i < jsonArr.length();i++)
						{
							JSONObject listing = ((JSONObject)jsonArr.get(i));
							sb.append("<div class=\"item\" id=\""+listing.get("zillowID")+"\">");
							sb.append("<div id=\"shortreport\"><h4 class=\"address\">"+listing.get("ADDRESS")+"</h4>");
							sb.append("<div id=\"photo\"><a class=\"fancyphotoLink\" id=\""+listing.get("zillowID")+"\" title=\""+listing.get("ADDRESS")+"\"><img class=\"listViewImage\" src=\""+listing.get("image_url")+"\"></a></div>");
							sb.append("<div class=\"listingfields\"><div><span class=\"label\">Price </span>"+(listing.has("price")?NumberFormat.getCurrencyInstance().format(Integer.parseInt((String) listing.get("price"))):"N/A")+"</div>");
							sb.append("<div><span class=\"label\">Bedrooms </span>"+listing.get("bedrooms")+"</div>");
							sb.append("<div><span class=\"label\">Bathrooms </span>"+listing.get("bathrooms")+"</div>");
							sb.append("<div><span class=\"label\">Property Type </span>"+listing.get("useCode")+"</div>");
							sb.append("<div><span class=\"label\">Square Feet </span>"+listing.get("finishedSQFT")+"</div>");
							sb.append("<div class=\"linkWrapper\" style=\"padding-top:5px;\" ><div id=\"detailview\"><a  id=\""+listing.get("zillowID")+"\" title=\""+listing.get("ADDRESS")+"\" class=\"detailLink moredetails\">More Details</a></div></div>");
							sb.append("</div></div></div>");
						}
						sb.append("</div></div></div>");
					
						sb.append("<script>");
						sb.append(DetailReport.javaScriptOut());
						sb.append("$('.fancyphotoLink').click(function(){var link = $(this); if(link.find('img').attr('src').indexOf('nophotoavail')==-1)$.post('"+Initialize.appURL()+"/ajaxCall.jsp?do=reports.Photos',{zillowID:link.attr('id')},function(data, textStatus, XMLHttpRequest) {"+
						"	if(data){$.fancybox(data,{title:link.attr('title'),type:'image', transitionIn:'elastic',transitionOut:'elastic',easingIn:'easeOutBack',easingOut:'easeInBack',width:500});}});}); ");
						sb.append("</script>");
						
						data.put("mapresults", jsonArr).put("searchresults", sb.toString()).put("count",jsonArr.length()).write(response.getWriter());
					}
				 catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

	
}
